import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:magma/storylines/home_story/rank_list_story.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../heartbeat/parts/magma_report_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 动态详情页面视图模型
class DynamicDetailNavigatorViewModel extends BaseViewModel {
  String _dynamicId = '';
  String get dynamicId => _dynamicId;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化数据
  void setupData(String dynamicId) {
    _dynamicId = dynamicId;
    notifyListeners();
  }

  /// 获取动态详情
  ContentModel? get dynamic {
    try {
      return appState.contentBroadcaster.dynamics.firstWhere(
        (d) => d.id == _dynamicId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取动态创建者信息
  UserModel? get dynamicCreator {
    if (dynamic == null) return null;
    try {
      return appState.userStore.getAllUsers().firstWhere(
        (u) => u.id == dynamic!.userId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取动态的评论列表
  List<ContentCommentModel> get comments {
    return appState.contentBroadcaster.retrieveComments(_dynamicId);
  }

  /// 获取推荐的动态列表（排除当前动态）
  List<ContentModel> get recommendedDynamics {
    return appState.contentBroadcaster.dynamics
        .where((d) => d.id != _dynamicId)
        .take(10)
        .toList();
  }

  /// 根据用户ID获取用户
  UserModel? getUserById(String userId) {
    try {
      return appState.userStore.getAllUsers().firstWhere((u) => u.id == userId);
    } catch (e) {
      return null;
    }
  }

  /// 检查当前用户是否关注了某个用户
  bool checkFollowingStatus(String targetUserId) {
    if (!isLoggedIn) return false;
    return appState.followManager.isFollowing(currentUser!.id, targetUserId);
  }

  /// 切换关注状态
  Future<bool> toggleFollowStatus(String targetUserId) async {
    if (!isLoggedIn) return false;

    final isFollowing = checkFollowingStatus(targetUserId);

    if (isFollowing) {
      final result = await appState.followManager.terminateFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      if (result) notifyListeners();
      return result;
    } else {
      final result = await appState.followManager.establishFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      if (result) notifyListeners();
      return result;
    }
  }

  /// 检查当前用户是否点赞了某个动态
  bool hasUserLiked(String dynamicId) {
    if (!isLoggedIn) return false;
    return appState.contentBroadcaster.likes.any(
      (like) => like.dynamicId == dynamicId && like.userId == currentUser!.id,
    );
  }

  /// 切换点赞状态
  Future<bool> toggleLike(String dynamicId) async {
    if (!isLoggedIn) return false;

    final result = await appState.contentBroadcaster.toggleAppreciation(
      dynamicId: dynamicId,
      userId: currentUser!.id,
    );

    if (result) notifyListeners();
    return result;
  }

  /// 发布评论
  Future<bool> publishComment(String content) async {
    if (!isLoggedIn) return false;
    if (content.trim().isEmpty) return false;

    final result = await appState.contentBroadcaster.appendComment(
      dynamicId: _dynamicId,
      userId: currentUser!.id,
      content: content,
    );

    if (result) notifyListeners();
    return result;
  }

  /// 删除动态
  Future<bool> deleteDynamic() async {
    if (dynamic == null) return false;

    final result = await appState.contentBroadcaster.removeContent(_dynamicId);

    return result;
  }

  /// 删除评论
  Future<bool> deleteComment(String commentId) async {
    final result = await appState.contentBroadcaster.removeComment(commentId);
    if (result) notifyListeners();
    return result;
  }
}

/// 动态详情页面
class DynamicDetailStory extends StatefulWidget {
  final String dynamicId;

  const DynamicDetailStory({super.key, required this.dynamicId});

  @override
  State<DynamicDetailStory> createState() => _DynamicDetailStoryState();
}

class _DynamicDetailStoryState extends State<DynamicDetailStory>
    with RouteAware, WidgetsBindingObserver {
  DynamicDetailNavigatorViewModel? _viewModel;
  RouteObserver<ModalRoute<dynamic>>? _routeObserver;
  final TextEditingController _commentController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null && route is PageRoute) {
      _routeObserver = RouteObserver<ModalRoute<dynamic>>();
      _routeObserver!.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    _routeObserver?.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    _commentController.dispose();
    super.dispose();
  }

  @override
  void didPopNext() {
    super.didPopNext();
    if (_viewModel != null) {
      _viewModel!.setupData(widget.dynamicId);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.setupData(widget.dynamicId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<DynamicDetailNavigatorViewModel>.reactive(
      viewModelBuilder: () => DynamicDetailNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
        viewModel.setupData(widget.dynamicId);
      },
      builder: (context, viewModel, child) {
        final dynamic = viewModel.dynamic;

        if (dynamic == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'Dynamic not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Stack(
            children: [
              // 主内容区域
              CustomScrollView(
                slivers: [
                  // 动态图片区域（固定在顶部）
                  SliverToBoxAdapter(
                    child: _buildDynamicImage(dynamic, viewModel),
                  ),

                  // 内容区域
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 20.h),

                          // 用户信息卡片
                          _buildUserInfoCard(viewModel),

                          SizedBox(height: 20.h),

                          // 动态标题
                          Text(dynamic.title).blackHanSans(
                            fontSize: 20.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w400,
                          ),

                          SizedBox(height: 12.h),

                          SizedBox(
                            width: double.infinity,
                            height: 1.h,
                            child: CustomPaint(painter: DashedLinePainter()),
                          ),
                          SizedBox(height: 12.h),

                          // 动态详情
                          Text(
                            dynamic.content,
                            style: TextStyle(height: 1.7),
                          ).inter(
                            fontSize: 16.sp,
                            color: MagmaColor.white.withOpacity(0.8),
                            fontWeight: FontWeight.w400,
                          ),

                          SizedBox(height: 30.h),

                          // 推荐标题
                          Text('Recommended').blackHanSans(
                            fontSize: 24.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w700,
                          ),

                          SizedBox(height: 12.h),
                        ],
                      ),
                    ),
                  ),

                  // 推荐动态列表
                  SliverToBoxAdapter(child: _buildRecommendedList(viewModel)),

                  // 评论标题和输入框
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 30.h),
                          Text('Comment').blackHanSans(
                            fontSize: 24.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w700,
                          ),
                          SizedBox(height: 12.h),
                          // 评论输入框
                          _buildCommentInputField(viewModel),
                          SizedBox(height: 20.h),
                        ],
                      ),
                    ),
                  ),

                  // 评论列表
                  SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      final comment = viewModel.comments[index];
                      return _buildCommentItem(comment, viewModel);
                    }, childCount: viewModel.comments.length),
                  ),

                  // 底部间距
                  SliverToBoxAdapter(child: SizedBox(height: 30.h)),
                ],
              ),

              // 标题栏
              _buildAppBar(context, viewModel),
            ],
          ),
        );
      },
    );
  }

  /// 构建动态图片区域
  Widget _buildDynamicImage(
    ContentModel dynamic,
    DynamicDetailNavigatorViewModel viewModel,
  ) {
    final isVideo = dynamic.type == ContentType.video;
    final imagePath =
        isVideo
            ? (dynamic.coverImagePath ?? MagmaConstant.dynamic1)
            : (dynamic.imagePath ?? MagmaConstant.dynamic1);

    return AspectRatio(
      aspectRatio: 414 / 412,
      child: Stack(
        children: [
          // 动态图片
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(imagePath),
                fit: BoxFit.cover,
              ),
            ),
          ),

          // 渐变蒙层（从顶部到底部）
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.black.withOpacity(0.1),
                  Colors.transparent,
                  Colors.black.withOpacity(0.1),
                ],
                stops: const [0.0, 0.3, 1.0],
              ),
            ),
          ),

          // 视频播放图标
          if (isVideo)
            Center(
              child: MagmaTap(
                onTap: () {
                  // 导航到视频播放页面
                  QR.to(
                    MagmaRouter.videoPlayerPath.replaceAll(
                      ':videoId',
                      dynamic.id,
                    ),
                  );
                },
                child: Icon(Icons.play_arrow, color: Colors.white, size: 40.w),
              ),
            ),

          // 装饰图片（底部）
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Image.asset(
              MagmaConstant.decoration,
              width: double.infinity,
              fit: BoxFit.fitWidth,
            ),
          ),

          // 点赞按钮（右下角）
          Positioned(
            right: 16.w,
            bottom: 36.h,
            child: StatefulBuilder(
              builder: (context, setState) {
                final isLiked = viewModel.hasUserLiked(dynamic.id);

                return MagmaTap(
                  onTap: () async {
                    if (!viewModel.isLoggedIn) {
                      await LoginRequiredDialog.show(context);
                      return;
                    }

                    final wasLiked = isLiked;
                    final result = await viewModel.toggleLike(dynamic.id);

                    if (result) {
                      setState(() {});
                      if (context.mounted) {
                        MagmaToast.success(
                          context,
                          title: wasLiked ? 'Unliked' : 'Liked',
                        );
                      }
                    }
                  },
                  child: Container(
                    width: 48.w,
                    height: 48.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Image.asset(
                        MagmaConstant.like,
                        width: 24.w,
                        height: 24.w,
                        color: isLiked ? Colors.red : Colors.white,
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户信息卡片
  Widget _buildUserInfoCard(DynamicDetailNavigatorViewModel viewModel) {
    final creator = viewModel.dynamicCreator;
    if (creator == null) return const SizedBox.shrink();

    return AspectRatio(
      aspectRatio: 374 / 90,
      child: Container(
        decoration: BoxDecoration(
          image: const DecorationImage(
            image: AssetImage(MagmaConstant.communityDetailUserCard),
            fit: BoxFit.cover,
          ),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Row(
            children: [
              // 用户头像
              MagmaTap(
                onTap: () {
                  QR.to(
                    MagmaRouter.otherUserPath.replaceAll(':userId', creator.id),
                  );
                },
                child: CircleAvatar(
                  radius: 29.r,
                  backgroundImage: AssetImage(creator.avatar),
                ),
              ),

              SizedBox(width: 12.w),

              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(creator.username).blackHanSans(
                      fontSize: 16.sp,
                      color: MagmaColor.black,
                      fontWeight: FontWeight.w400,
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      creator.signature,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ).inter(
                      fontSize: 16.sp,
                      color: MagmaColor.black.withOpacity(0.6),
                      fontWeight: FontWeight.w400,
                    ),
                  ],
                ),
              ),

              // 关注按钮
              StatefulBuilder(
                builder: (context, setState) {
                  final isFollowing = viewModel.checkFollowingStatus(
                    creator.id,
                  );
                  final isSelf =
                      viewModel.isLoggedIn &&
                      viewModel.currentUser?.id == creator.id;

                  if (isSelf) return const SizedBox.shrink();

                  return MagmaTap(
                    onTap: () async {
                      if (!viewModel.isLoggedIn) {
                        if (!mounted) return;
                        await LoginRequiredDialog.show(context);
                        return;
                      }

                      // 检查是否是关注自己
                      if (viewModel.currentUser?.id == creator.id) {
                        if (!mounted) return;
                        MagmaToast.error(
                          context,
                          title: 'You cannot follow yourself',
                        );
                        return;
                      }

                      final wasFollowing = isFollowing;
                      final result = await viewModel.toggleFollowStatus(
                        creator.id,
                      );

                      if (result) {
                        setState(() {});
                        if (!mounted) return;
                        MagmaToast.success(
                          context,
                          title: wasFollowing ? 'Unfollowed' : 'Followed',
                        );
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 8.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            isFollowing
                                ? MagmaColor.black.withOpacity(0.1)
                                : MagmaColor.purple,
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      child: Text(
                        isFollowing ? 'Following' : '+Follow',
                        style: TextStyle(
                          fontFamily:
                              GoogleFonts.rowdies(
                                fontSize: 16.sp,
                                color:
                                    isFollowing
                                        ? MagmaColor.black
                                        : MagmaColor.white,
                                fontWeight: FontWeight.w600,
                              ).fontFamily,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建推荐动态列表
  Widget _buildRecommendedList(DynamicDetailNavigatorViewModel viewModel) {
    return SizedBox(
      height: 136.w,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        itemCount: viewModel.recommendedDynamics.length,
        itemBuilder: (context, index) {
          final dynamic = viewModel.recommendedDynamics[index];
          return _buildRecommendedItem(dynamic, viewModel);
        },
      ),
    );
  }

  /// 构建推荐动态单项
  Widget _buildRecommendedItem(
    ContentModel dynamic,
    DynamicDetailNavigatorViewModel viewModel,
  ) {
    return MagmaTap(
      onTap: () {
        // 导航到新的动态详情页
        QR.to(
          MagmaRouter.dynamicDetailPath.replaceAll(':dynamicId', dynamic.id),
        );
      },
      child: Container(
        width: 136.w,
        margin: EdgeInsets.only(right: 12.w),
        child: AspectRatio(
          aspectRatio: 136 / 136,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(2.r),
            child: Stack(
              children: [
                // 动态图片
                Container(
                  width: double.infinity,
                  height: double.infinity,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        dynamic.imagePath ??
                            dynamic.coverImagePath ??
                            MagmaConstant.dynamic1,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),

                // 渐变蒙层
                Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.6),
                      ],
                    ),
                  ),
                ),

                // 用户信息和标题
                Positioned(
                  left: 8.w,
                  right: 8.w,
                  bottom: 8.h,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 用户信息
                      Row(
                        children: [
                          // 用户头像
                          MagmaTap(
                            onTap: () {
                              QR.to(
                                MagmaRouter.otherUserPath.replaceAll(
                                  ':userId',
                                  dynamic.userId,
                                ),
                              );
                            },
                            child: CircleAvatar(
                              radius: 12.r,
                              backgroundImage: AssetImage(
                                viewModel.getUserById(dynamic.userId)?.avatar ??
                                    MagmaConstant.avatar1,
                              ),
                            ),
                          ),

                          SizedBox(width: 4.w),

                          // 用户名
                          Expanded(
                            child: Text(
                              viewModel.getUserById(dynamic.userId)?.username ??
                                  'Unknown',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ).inter(
                              fontSize: 12.sp,
                              color: MagmaColor.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建评论单项
  Widget _buildCommentItem(
    ContentCommentModel comment,
    DynamicDetailNavigatorViewModel viewModel,
  ) {
    final user = viewModel.getUserById(comment.userId);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: MagmaColor.white.withOpacity(0.15),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户头像
              MagmaTap(
                onTap: () {
                  QR.to(
                    MagmaRouter.otherUserPath.replaceAll(
                      ':userId',
                      comment.userId,
                    ),
                  );
                },
                child: CircleAvatar(
                  radius: 24.r,
                  backgroundImage: AssetImage(
                    user?.avatar ?? MagmaConstant.avatar1,
                  ),
                ),
              ),

              SizedBox(width: 12.w),

              // 评论内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名
                    Text(user?.username ?? 'Unknown').inter(
                      fontSize: 14.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w600,
                    ),

                    SizedBox(height: 4.h),

                    // 评论文本
                    Padding(
                      padding: EdgeInsets.only(right: 24.w),
                      child: Text(comment.content).inter(
                        fontSize: 13.sp,
                        color: MagmaColor.white,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          // 举报按钮（右上角）
          Positioned(
            top: 0,
            right: 0,
            child: MagmaTap(
              onTap: () async {
                await MagmaReportDialog.showReportDialog(
                  context,
                  title: 'Report Comment',
                  subtitle: 'Please select a reason for reporting this comment',
                  onReportSubmitted: (option) async {
                    // 删除评论
                    await viewModel.deleteComment(comment.id);
                    MagmaToast.success(
                      context,
                      title: 'You won\'t see this again.',
                    );
                  },
                );
              },
              child: Image.asset(
                MagmaConstant.commentReport,
                width: 20.w,
                height: 20.w,
                color: MagmaColor.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标题栏
  Widget _buildAppBar(
    BuildContext context,
    DynamicDetailNavigatorViewModel viewModel,
  ) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top + 16.h,
          left: 20.w,
          right: 20.w,
          bottom: 16.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.black.withOpacity(0.6), Colors.transparent],
          ),
        ),
        child: Row(
          children: [
            MagmaTap(
              onTap: () => QR.back(),
              child: Image.asset(
                MagmaConstant.back,
                width: 24.w,
                height: 24.w,
                color: MagmaColor.white,
              ),
            ),
            Expanded(
              child: Center(
                child: Text('Details').blackHanSans(
                  fontSize: 24.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
            // 举报按钮
            MagmaTap(
              onTap: () async {
                await MagmaReportDialog.showReportDialog(
                  context,
                  title: 'Report Content',
                  subtitle: 'Please select a reason for reporting this content',
                  onReportSubmitted: (option) async {
                    // 删除动态
                    final result = await viewModel.deleteDynamic();
                    if (result) {
                      if (!mounted) return;
                      MagmaToast.success(
                        context,
                        title: 'You won\'t see this content again',
                      );
                      QR.back();
                    }
                  },
                );
              },
              child: Image.asset(
                MagmaConstant.report,
                width: 26.w,
                height: 26.w,
                color: MagmaColor.white,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建评论输入框（放在评论标题下方）
  Widget _buildCommentInputField(DynamicDetailNavigatorViewModel viewModel) {
    return SizedBox(
      height: 56.h,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 用户头像或占位符
          Container(
            width: 56.w,
            height: 56.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color:
                  viewModel.isLoggedIn
                      ? null
                      : MagmaColor.white.withOpacity(0.15),
            ),
            child:
                viewModel.isLoggedIn
                    ? ClipOval(
                      child: Image.asset(
                        viewModel.currentUser?.avatar ?? MagmaConstant.avatar1,
                        fit: BoxFit.cover,
                      ),
                    )
                    : Center(
                      child: Icon(
                        Icons.person_outline,
                        color: MagmaColor.white.withOpacity(0.3),
                        size: 28.w,
                      ),
                    ),
          ),

          SizedBox(width: 12.w),

          // 输入框（包含发送按钮）
          Expanded(
            child: Container(
              height: 56.h,
              decoration: BoxDecoration(
                color: MagmaColor.white.withOpacity(0.15),
                borderRadius: BorderRadius.circular(28.r),
              ),
              child: Row(
                children: [
                  // 输入框
                  Expanded(
                    child: TextField(
                      controller: _commentController,
                      style: GoogleFonts.inter(
                        fontSize: 14.sp,
                        color: MagmaColor.white,
                        fontWeight: FontWeight.w400,
                      ),
                      decoration: InputDecoration(
                        hintText: 'Post a comment',
                        hintStyle: GoogleFonts.inter(
                          fontSize: 14.sp,
                          color: MagmaColor.white.withOpacity(0.4),
                          fontWeight: FontWeight.w400,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 16.h,
                        ),
                      ),
                    ),
                  ),

                  // 发送按钮
                  Padding(
                    padding: EdgeInsets.only(right: 8.w),
                    child: MagmaTap(
                      onTap: () async {
                        if (!viewModel.isLoggedIn) {
                          if (!mounted) return;
                          await LoginRequiredDialog.show(context);
                          return;
                        }

                        final content = _commentController.text.trim();
                        if (content.isEmpty) {
                          if (!mounted) return;
                          MagmaToast.error(
                            context,
                            title: 'Please enter a comment',
                          );
                          return;
                        }

                        final result = await viewModel.publishComment(content);
                        if (result) {
                          _commentController.clear();
                          if (!mounted) return;
                          FocusScope.of(context).unfocus();
                          MagmaToast.success(context, title: 'Comment posted');
                        } else {
                          if (!mounted) return;
                          MagmaToast.error(
                            context,
                            title: 'Failed to post comment',
                          );
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          color: MagmaColor.purple,
                          shape: BoxShape.circle,
                        ),
                        child: Image.asset(
                          MagmaConstant.send,
                          width: 24.w,
                          height: 24.w,
                          color: MagmaColor.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
